<template>
    <div>
        <UserLayout>
            <div class="engine-wrap">
                <div class="app-card">
                    <div class="app-card-header">
                        <span>引擎</span>
                        <div class="header-setting">
                            <a-tooltip>
                                <template v-slot:title>发现</template>
                                <a-button
                                        type="dashed"
                                        shape="circle"
                                        size="small"
                                        @click="gotoUrl('/store?type=engine')"
                                >
                                    <template #icon>
                                        <AppstoreAddOutlined />
                                    </template>
                                </a-button>
                            </a-tooltip>
                            <a-tooltip>
                                <template v-slot:title>新增引擎</template>
                                <a-button
                                        class="margin-left"
                                        type="dashed"
                                        shape="circle"
                                        size="small"
                                        @click="openEngineModal"
                                >+
                                </a-button>
                            </a-tooltip>
                        </div>
                    </div>
                    <div class="app-card-body">
                        <ul class="engine-box" @dragstart="onDragEngineStart" @dragover="onDragOver"
                            @dragend="onDragEnd('engine')" ref="engine" v-if="engine.list.length">
                            <li class="item text-elip" draggable="true" v-for="(item,index) in engine.list" :key="index"
                                :data-id="item.id">
                                <img class="engine-img" :src="item.icon" alt="">
                                <div class="item-text text-elip">{{item.title}}</div>
                                <a-button class="item-edit" size="small" @click="showEditEngineModal(index)">
                                    <template #icon>
                                        <EditOutlined/>
                                    </template>
                                </a-button>
                                <a-popconfirm title="确认操作?" ok-text="是" cancel-text="否" @confirm="delEngineOk(item.id)">
                                    <a-button class="item-del" type="danger" size="small">
                                        <template #icon>
                                            <DeleteOutlined/>
                                        </template>
                                    </a-button>
                                </a-popconfirm>
                            </li>
                        </ul>
                        <div class="text-center" v-else>暂无数据</div>
                    </div>
                </div>
            </div>
        </UserLayout>

        <!-- 引擎 -->
        <a-modal title="新增" v-model:visible="engine.state" @ok="engineOk">
            <a-form layout="vertical">
                <a-form-item :label="'搜索引擎链接 如:' + website.defaultEngine">
                    <a-input v-model:value="engine.form.url" placeholder="请输入搜索引擎链接"/>
                </a-form-item>
                <a-form-item label="引擎标题">
                    <a-input v-model:value="engine.form.title" placeholder="请输入引擎标题"/>
                </a-form-item>
            </a-form>
        </a-modal>
        <a-modal title="编辑" v-model:visible="engine.editState" @ok="editEngineOk">
            <a-form layout="vertical">
                <a-form-item :label="'搜索引擎链接 如:' + website.defaultEngine">
                    <a-input v-model:value="engine.editForm.url" placeholder="请输入搜索引擎链接"/>
                </a-form-item>
                <a-form-item label="引擎标题">
                    <a-input v-model:value="engine.editForm.title" placeholder="请输入引擎标题"/>
                </a-form-item>
            </a-form>
        </a-modal>
    </div>
</template>

<script>
    import UserLayout from '/src/components/user/Layout.vue';

    import website from '/src/config/website';
    import {clearStorage, goUrl} from '/src/util/index';
    import {
        orderEngine,
        orderMenu,
        orderBookmark,
        delEngine,
        addEngine,
        editEngine
    } from '/src/request/api/nav';

    // iconfont
    import {
        AppstoreAddOutlined,
        EditOutlined,
        DeleteOutlined,
    } from '@ant-design/icons-vue';

    export default {
        // 组件
        components: {
            UserLayout,
            AppstoreAddOutlined,
            EditOutlined,
            DeleteOutlined,
        },
        // 数据
        data() {
            return {
                website: website,
                // 搜索引擎
                engine: {
                    list: [],
                    idx: 0,
                    row: null,
                    state: false,
                    form: {
                        url: '',
                        title: '',
                    },

                    editState: false,
                    editForm: {
                        id: '',
                        url: '',
                        title: '',
                    }
                },
                // 被拖拽的对象
                draging: null,
                // 目标对象
                target: null,
                // ref
                ref: null,
            }
        },
        // DOM未渲染前调用
        created() {
            this.getEngine(true);
        },
        // DOM渲染后调用
        mounted() {
            // 为了防止火狐浏览器拖拽的时候以新标签打开
            document.body.ondrop = function (event) {
                event.preventDefault();
                event.stopPropagation();
            }
        },
        // 方法
        methods: {
            gotoUrl(url) {
                goUrl(url);
            },
            // engine
            getEngine(refresh = false) {
                let that = this;
                that.$store.dispatch('getEngine', refresh).then(list => {
                    console.log('getEngine', list);
                    that.engine.list = list;
                    if (list.length) {
                        that.engine.row = list[0];
                    }
                });
            },
            // openEngineModal
            openEngineModal() {
                this.engine.state = true;
            },
            // engineOk
            engineOk() {
                let that = this,
                    form = that.engine.form,
                    data = {
                        url: form.url,
                        title: form.title,
                    };
                if (!data.url) {
                    that.$message.warning('缺少必要参数: url');
                    return false;
                }
                if (!data.title) {
                    that.$message.warning('缺少必要参数: title');
                    return false;
                }
                addEngine(data).then(res => {
                    that.$message.success(res.msg || website.msg.success);
                    that.engine.state = false;
                    that.engine.form.url = '';
                    that.engine.form.title = '';
                    that.getEngine(true);
                }).catch(err => {
                    that.$message.error(err.msg || website.msg.error);
                })
            },
            // showEditEngineModal
            showEditEngineModal(index) {
                let that = this,
                    list = that.engine.list,
                    row = list[index],
                    form = {
                        id: row.id,
                        title: row.title,
                        url: row.url,
                    };
                that.engine.editForm = form;
                this.engine.editState = true;
            },
            // editEngineOk
            editEngineOk() {
                let that = this,
                    form = that.engine.editForm;
                editEngine(form).then(res => {
                    that.$message.success(res.msg || website.msg.success);
                    that.engine.editState = false;
                    that.getEngine(true);
                }).catch(err => {
                    that.$message.error(err.msg || website.msg.error);
                })
            },
            // delEngineOk
            delEngineOk(id) {
                let that = this;
                delEngine({
                    id: id,
                }).then(res => {
                    that.$message.success(res.msg || website.msg.success);
                    that.getEngine(true);
                }).catch(err => {
                    that.$message.error(err.msg || website.msg.error);
                })
            },

            // 拖动
            onDragEngineStart(event) {
                console.log("drag start");
                this.draging = event.target;
                this.ref = 'engine';
            },
            onDragOver(event) {
                console.log('drag move');
                this.target = event.target;
                let targetTop = event.target.getBoundingClientRect().top;
                let dragingTop = this.draging.getBoundingClientRect().top;
                if (this.target.nodeName === "LI" && this.target !== this.draging) {
                    if (this.target) {
                        if (this.target.animated) {
                            return;
                        }
                    }
                    if (this._index(this.draging) < this._index(this.target)) {
                        this.target.parentNode.insertBefore(this.draging, this.target.nextSibling);
                    } else {
                        this.target.parentNode.insertBefore(this.draging, this.target);
                    }
                    this._anim(targetTop, this.target);
                    this._anim(dragingTop, this.draging);
                }
            },
            onDragEnd(type) {
                console.log('drag end');
                let that = this,
                    currentNodes = Array.from(that.getChildNodes());

                let data = currentNodes.map((i, index) => {
                    let ref = that.ref,
                        list = [];
                    // engine
                    if (ref == 'engine') {
                        list = that.engine.list;
                    }
                    // nav
                    else if (ref == 'nav') {
                        list = that.nav.list;
                    }
                    // bookmark
                    else if (ref == 'bookmark') {
                        list = that.bookmark.list;
                    } else {
                        that.$message.error('ref error');
                    }
                    let item = list.find(c => c.id == (i && i.dataset && i.dataset.id ? i.dataset.id : ''));
                    if (item) {
                        return item.id;
                    }
                });
                // 搜索引擎排序
                if (type == 'engine') {
                    orderEngine({
                        order: JSON.stringify(data),
                    }).then(res => {
                        that.$message.success(res.msg || website.msg.success);
                        clearStorage();
                        //window.location.reload();
                    }).catch(err => {
                        that.$message.error(err.msg || website.msg.error);
                    })
                }
                // 分类排序
                else if (type == 'nav') {
                    orderMenu({
                        order: JSON.stringify(data),
                    }).then(res => {
                        that.$message.success(res.msg || website.msg.success);
                        clearStorage();
                        //window.location.reload();
                    }).catch(err => {
                        that.$message.error(err.msg || website.msg.error);
                    })
                }
                // 书签排序
                else if (type == 'bookmark') {
                    orderBookmark({
                        order: JSON.stringify(data),
                    }).then(res => {
                        that.$message.success(res.msg || website.msg.success);
                        clearStorage();
                        //window.location.reload();
                    }).catch(err => {
                        that.$message.error(err.msg || website.msg.error);
                    })
                }
            },
            _anim(startPos, dom) {
                let offset = startPos - dom.getBoundingClientRect().top;
                dom.style.transition = "none";
                dom.style.transform = `translateY(${offset}px)`;
                //触发重绘
                dom.offsetWidth;
                dom.style.transition = "transform .3s";
                dom.style.transform = ``;
                clearTimeout(dom.animated);

                dom.animated = setTimeout(() => {
                    dom.style.transition = "";
                    dom.style.transform = ``;
                    dom.animated = false;
                }, 300)
            },
            _index(el) {
                let domData = Array.from(this.getChildNodes());
                return domData.findIndex(i => i.innerText == el.innerText);
            },
            getChildNodes(ref = this.ref) {
                return this.$refs[ref].childNodes;
            },
        }
    }
</script>

<style lang="less" scoped>
    @width: 1000px;
    @height: 20px;
    @radius: 4px;
    @itemHeight: 20px;

    .engine-wrap {
        .engine-title {
            height: 30px;
            font-size: 16px;
        }

        .engine-box {
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
            overflow-x: hidden;
            overflow-y: auto;

            .engine-img {
                position: relative;
                width: @height;
                height: @height;
                display: block;
                float: left;
                margin-right: 5px;

                &:after {
                    content: '';
                    display: block;
                    width: 100%;
                    height: 100%;
                    position: absolute;
                    z-index: 2;
                    top: 0;
                    left: 0;
                    background: url('/src/assets/imgs/network.png') white;
                    background-size: 100%;
                }
            }

            .engine-count {
                display: inline-block;
                float: right;
                border-radius: @radius;
                color: #959595;
                padding: 0 5px;
                font-size: 12px;
            }
        }
    }

    ul {
        list-style: none;
    }

    .item {
        display: flex;
        align-items: center;
        font-size: 14px;
        line-height: @height;
        cursor: pointer;
        min-height: @height;
        color: black;
        border: 1px solid #d4d4d4;
        border-radius: @radius;
        margin-top: 5px;
        padding: 4px;
        text-align: left;

        &.active {
            border-left: 5px solid #1E9FFF;
        }

        .item-text {
            flex: 1;
        }

        .item-edit {
            margin-left: 10px;
        }

        .item-del {
            margin-left: 10px;
        }

        &:first-child {
            margin: 0;
        }
    }

    @media screen and (max-width: @width + 40) {
        .manage-wrap .main-wrap {
            width: auto;
            overflow: hidden;
            margin: 0;
            padding: 0 20px 20px 20px;
        }
    }
</style>